import time,os,sys,logging
from logging.handlers import TimedRotatingFileHandler
from datetime import datetime
## 日志类
class Logger:
    def __init__(self):
        self.current_date = datetime.now().strftime("%Y-%m-%d")
        self._setup_logging()


    def _setup_logging(self):
        """初始化简化的日志系统"""
        try:
            # 创建logs目录
            logs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logs')
            if not os.path.exists(logs_dir):
                os.makedirs(logs_dir, exist_ok=True)

            # 设置信号日志文件 - 使用日期格式
            log_file = os.path.join(logs_dir, f'signals_{self.current_date}.log')

            # 创建logger
            self.signal_logger = logging.getLogger("signals")
            self.signal_logger.setLevel(logging.INFO)
            self.signal_logger.propagate = False

            # 清除已有的handlers
            for handler in self.signal_logger.handlers[:]:
                self.signal_logger.removeHandler(handler)

            # 添加文件handler - 使用简单的FileHandler，因为文件名已经包含日期
            file_handler = logging.FileHandler(
                filename=log_file,
                encoding="utf-8"
            )
            formatter = logging.Formatter(
                "%(asctime)s - %(levelname)s - %(message)s",
                datefmt="%Y-%m-%d %H:%M:%S"
            )
            file_handler.setFormatter(formatter)
            self.signal_logger.addHandler(file_handler)

        except Exception as e:
            # 日志系统初始化失败时，直接打印错误信息
            print(f"⚠️ 日志系统初始化失败: {e}")
            self.signal_logger = None

    def _check_date_change(self):
        """检查日期是否变化，如果变化则重新初始化日志系统"""
        today = datetime.now().strftime("%Y-%m-%d")
        if today != self.current_date:
            self.current_date = today
            self._setup_logging()

    def log_signal(self, msg: str, level: str = "info"):
        """记录交易信号到日志文件"""
        # 检查日期变化
        self._check_date_change()
        
        if hasattr(self, 'signal_logger') and self.signal_logger:
            try:
                if level == "warning":
                    self.signal_logger.warning(msg)
                elif level == "error":
                    self.signal_logger.error(msg)
                else:
                    self.signal_logger.info(msg)
            except Exception:
                pass
        # 同时输出到控制台
        print(msg)
    def log_msg(self, msg: str, level: str = "info"):
        """记录交易信号到日志文件"""
        # 检查日期变化
        self._check_date_change()
        
        if hasattr(self, 'signal_logger') and self.signal_logger:
            try:
                if level == "warning":
                    self.signal_logger.warning(msg)
                elif level == "error":
                    self.signal_logger.error(msg)
                else:
                    self.signal_logger.info(msg)
            except Exception:
                pass
        # 同时输出到控制台
        print(msg)